import {
	sub
} from '@/common/event.js'

import store from '@/store/index.js'
import request from '@/common/request.js'
export default {
	namespaced: true,
	state: {
		friends: [],
		apply:0
	},
	mutations: {
		clearAll: (state, payload) => {
			state.friends = []
			state.apply = 0
		},
		setFriendsState: (state, payload) => {
			state.friends = payload
		},
		setApplyState: (state, payload) => {
			state.apply = payload
		},
		addFriendState: (state, payload) => {
			state.friends.push(payload)
		},
	},
	actions: {
		async refreshApply({commit},{payload}){
			const user = uni.getStorageSync("user")
			const id = user.id * 1
			const sumRet = await request.getRqst().get(`/user/user/getApplysSum`,{id})
			commit('setApplyState', sumRet.data[0].sum)
		},
		async refreshFriends({commit},{payload}){
			const user = uni.getStorageSync("user")
			const id = user.id * 1
			const ret = await request.getRqst().get(`/friend/friend/${id}`)
			commit('setFriendsState', ret.data)
		},
		async initFriendsAndApplySum({
			commit
		}, {
			payload
		}) {
			const user = uni.getStorageSync("user")
			console.log("vuex action store.state.user", request)
			const id = user.id * 1
			const ret = await request.getRqst().get(`/friend/friend/${id}`)
			commit('setFriendsState', ret.data)
			const sumRet = await request.getRqst().get(`/user/user/getApplysSum`,{id})
			commit('setApplyState', sumRet.data[0].sum)
		},
	},
	init: function() {
		console.log(`执行初始化`,request)
		const user = uni.getStorageSync("user")
		if(user){
			store.dispatch(`address/initFriendsAndApplySum`,{})
		}
		sub(`loginSuccess`,function(e){
			store.dispatch(`address/initFriendsAndApplySum`,{})
		})
		
		sub(`socket_friendApply`,function(e){
			store.commit('address/setApplyState', store.state.address.apply + 1)
		})
		
		sub(`logout`,function(e){
			store.commit('address/clearAll', {})
		})
	}
}